package com.mt.mtbletools;

import com.mt.help.GlobalVariable;
import com.mt.sdk.ble.MTBLEDevice;
import com.mt.sdk.ble.MTBLEManager;
import com.mt.sdk.ble.base.TIOADBase;
import com.mt.sdk.ble.model.ErroCode;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class OADActivity extends Activity {
	private GlobalVariable mGlobalVariable;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_oad);

		mGlobalVariable = GlobalVariable.getinstance();

		getDefaultDatas();

		initView();

		initBLE();
		
		keyOnScream();
	}

	// 获取传送过来的数据
	private MTBLEDevice device;
	private int index;

	private void getDefaultDatas() {
		index = getIntent().getIntExtra(ScanFragment.SELECTDEVICE, -1);
		if (index == -1) {
			finish();
			return;
		}
		if (mGlobalVariable.getDeviceList().size() == 0) {
			finish();
			return;
		}
		device = mGlobalVariable.getDeviceList().get(index);
	}

	// 申请电源锁，禁止休眠
	private WakeLock mWakeLock = null;

	public void keyOnScream() {
		if (null == mWakeLock) {
			PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
			mWakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, this.getClass().getCanonicalName());
			if (null != mWakeLock) {
				mWakeLock.acquire();
			}
		}
	}

	// 释放设备电源锁
	public void releaseOnScream() {
		if (null != mWakeLock) {
			mWakeLock.release();
			mWakeLock = null;
		}
	}

	// 初始化控件
	private Button fileselect_btn;
	private Button startupdata_btn;
	private TextView deivce_version_txt;
	private TextView deivce_lenght_txt;
	private TextView deivce_filetype_txt;
	private TextView file_version_txt;
	private TextView file_lenght_txt;
	private TextView file_filetype_txt;
	private TextView updateprocess_txt;
	private TextView workstatues_txt;

	private void initView() {
		fileselect_btn = (Button) findViewById(R.id.fileselect_btn);
		startupdata_btn = (Button) findViewById(R.id.startupdata_btn);

		deivce_version_txt = (TextView) findViewById(R.id.deivce_version_txt);
		deivce_lenght_txt = (TextView) findViewById(R.id.deivce_lenght_txt);
		deivce_filetype_txt = (TextView) findViewById(R.id.deivce_filetype_txt);
		file_version_txt = (TextView) findViewById(R.id.file_version_txt);
		file_lenght_txt = (TextView) findViewById(R.id.file_lenght_txt);
		file_filetype_txt = (TextView) findViewById(R.id.file_filetype_txt);
		updateprocess_txt = (TextView) findViewById(R.id.updateprocess_txt);
		workstatues_txt = (TextView) findViewById(R.id.workstatues_txt);

		fileselect_btn.setOnClickListener(myOnClickListener);
		startupdata_btn.setOnClickListener(myOnClickListener);
	}

	// 初始化蓝牙
	private MTBLEManager manger;
	private TIOADBase mBle;

	private void initBLE() {
		manger = MTBLEManager.getInstance(getApplicationContext());
		mBle = new TIOADBase(getApplicationContext(), manger);

		mBle.connect(device.getDevice().getAddress(), 2, false, callback);
	}

	// 连接回调
	private TIOADBase.CallBack callback = new TIOADBase.CallBack() {

		@Override
		public void reTryConnect(int lasttimes) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onUpdataResult(ErroCode erro) {
			if (erro.getCode() != 0) { // 升级失败
				workstatues_txt.setText("升级失败->" + erro.getMsg());
				return;
			}
			workstatues_txt.setText("升级成功");
		}

		@Override
		public void onUpdata(int process) {
			updateprocess_txt.setText("升级进度:" + process + "/" + oadfile.getFile_nBlocks());
		}

		@Override
		public void onReadInf(int version, int len, Character imgType, byte[] uid, ErroCode erro) {
			System.out.println("onReadInf");
			if (erro.getCode() != 0) {
				return;
			}

			if ((oadfile != null) && (imgType != oadfile.getFileimgType())) {
				startupdata_btn.setEnabled(true);
			} else {
				startupdata_btn.setEnabled(false);
			}

			deivce_version_txt.setText("Version:" + version);
			deivce_lenght_txt.setText("Lenght:" + len);
			deivce_filetype_txt.setText("ImgType:" + imgType);
		}

		@Override
		public void onManualDisConnect(ErroCode errocode) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onDisConnect(ErroCode errocode) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onConnect(ErroCode errocode) {

			if (errocode.getCode() != 0) {
				return;
			}
			mBle.readDeviceInf(); // 读取
		}
	};

	// 按键监听
	private static final String FW_CUSTOM_DIRECTORY = Environment.DIRECTORY_DOWNLOADS;
	private static final int FILE_ACTIVITY_REQ = 4;
	private OnClickListener myOnClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			if (v == fileselect_btn) {
				Intent i = new Intent(getApplicationContext(), FileActivity.class);
				i.putExtra(FileActivity.EXTRA_MESSAGE, FW_CUSTOM_DIRECTORY);
				startActivityForResult(i, FILE_ACTIVITY_REQ);
				return;
			}

			if (v == startupdata_btn) {
				mBle.upDatas(oadfile);
				return;
			}
		}
	};

	private TIOADBase.OADFile oadfile;

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == FILE_ACTIVITY_REQ) {
			if (resultCode == RESULT_OK) {
				String filename = data.getStringExtra(FileActivity.EXTRA_FILENAME);
				oadfile = TIOADBase.OADFile.getFile(filename);

				if (oadfile != null) {
					file_version_txt.setText("Version:" + oadfile.getFileversion());
					file_lenght_txt.setText("Lenght:" + oadfile.getFilelenght());
					file_filetype_txt.setText("ImgType:" + oadfile.getFileimgType());

					if ((mBle.getDeviceimgType() != 'D') && (mBle.getDeviceimgType() != oadfile.getFileimgType())) {
						startupdata_btn.setEnabled(true);
					} else {
						startupdata_btn.setEnabled(false);
					}
				} else {
					startupdata_btn.setEnabled(false);
				}
			}
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		
		mBle.disConnect();
		releaseOnScream();
	}
}
